package org.example.websocket.spring.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * 实现 WebSocketConfigurer 类并覆盖相应的方法进行 websocket 的配置
 */
@Configuration
@EnableWebSocket
public class SpringWebSocketServerConfig implements WebSocketConfigurer {

    @Autowired
    private WebSocketServerHandler httpAuthHandler;

    @Autowired
    private HttpAuthInterceptor myInterceptor;

    /**
     * 覆盖 registerWebSocketHandlers 这个方法。通过向 WebSocketHandlerRegistry 设置不同参数来进行配置
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                // 添加ws的handler处理类
                .addHandler(httpAuthHandler, "/spring/ws")
                .addInterceptors(myInterceptor)
                // 关闭跨域校验，方便本地调试，线上推荐打开
                .setAllowedOrigins("*");
    }
}